package com.mingyizhudao.app.view.recommend;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.TextAppearanceSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dixiang.framework.common.QJNetUICallback;
import com.dixiang.framework.common.QJNetUICallback2;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.config.SystemConfig;
import com.dixiang.framework.network2.NetOld;
import com.dixiang.framework.utils.AlertDialogs;
import com.dixiang.framework.utils.BitmapCache;
import com.dixiang.framework.utils.Utils;
import com.dixiang.framework.widget.LoadingDialog;
import com.google.gson.reflect.TypeToken;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.moudle.bitmap.BimpTempHelper;
import com.mingyizhudao.app.moudle.bitmap.ImageGridActivity;
import com.mingyizhudao.app.moudle.bitmap.ImageItem;
import com.mingyizhudao.app.moudle.bitmap.NoScrollGridView;
import com.mingyizhudao.app.moudle.bitmap.PhotoActivity;
import com.mingyizhudao.app.utils.CommonUtils;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.utils.IntentHelper;
import com.mingyizhudao.app.utils.ToastUtil;
import com.mingyizhudao.app.utils.UploadUtil;
import com.mingyizhudao.app.utils.UploadUtils;
import com.mingyizhudao.app.utils.UploadUtils.OnLoadListener;
import com.mingyizhudao.app.view.MYBaseActivity;
import com.mingyizhudao.app.view.PayViewActivity;
import com.mingyizhudao.app.view.WebViewActivity;
import com.mingyizhudao.app.view.doctor.DoctorListActivity;
import com.mingyizhudao.app.view.mine.OrderListActivity;
import com.mingyizhudao.app.view.recommend.bean.OrderResutEntity;

public class CreateOrderActivity extends MYBaseActivity implements OnClickListener{
	private NoScrollGridView noScrollgridview;
	private GridAdapter adapter;
	private String parm_doctor_id;
	private String parm_doctor_name;
	private String parm_doctor_dept;
	private String parm_doctor_hp;
	private boolean parm_order_isteam;
	private BitmapCache cache;
	private List<ImageItem> dataChoosed = new ArrayList<ImageItem>();// 选中的item
	private Handler handler = new Handler();

	private Button btn_add_pic ;
	private EditText et_username,  et_disasename, et_disease_des;
	private String userName, disaseName, disaseDes;
	private static final int FAIL = 500;// 更新下载进度的标记
	private static final int SUCCESS = 200;
	private ProgressDialog progressDialog;

	private String payUrl;
	private String bookingId;
	private boolean isAdd = true;//如果有添加按钮false
	private boolean is_commonweal;
	
	
	private CheckBox cb_agree;
	private TextView tv_agreement;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_create);
		initData();
		initView();
		cache = new BitmapCache(this, Constants.PHOTOWIDTH);
	}

	private void initData() {
		parm_doctor_id = getIntent().getStringExtra(
				Constants.ORDER.PARM_ORDER_DOCTOR_ID);
		parm_doctor_name = getIntent().getStringExtra(
				Constants.ORDER.PARM_ORDER_DOCTOR_NAME);
		parm_doctor_dept = getIntent().getStringExtra(
				Constants.ORDER.PARM_ORDER_DOCTOR_DEPT);
		parm_doctor_hp = getIntent().getStringExtra(
				Constants.ORDER.PARM_ORDER_DOCTOR_HP);
		//parm_action_url = getIntent().getStringExtra(Constants.PARM_ACTION_URL);
		parm_order_isteam =  getIntent().getBooleanExtra(
				Constants.PARM_ORDER_TYPE, false);
		
		is_commonweal = getIntent().getBooleanExtra(Constants.PARM_ORDER_COMMONWEAL, false);
	}

	private void initView() {
		progressDialog = new ProgressDialog(this);
		progressDialog.setCanceledOnTouchOutside(false);
		
		progressDialog.setMessage("上传中...");

		cb_agree = (CheckBox) findViewById(R.id.cb_agree);
		tv_agreement = (TextView) findViewById(R.id.tv_agreement);
		tv_agreement.setOnClickListener(this);
		
		final Button btn_commit = (Button) findViewById(R.id.btn_commit);
		if (!cb_agree.isChecked()) {
			btn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_can_not));
			btn_commit.setClickable(false);
		}
		cb_agree.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					btn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_gold_cyan_bg));
					btn_commit.setClickable(true);
				}else {
					btn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_can_not));
					btn_commit.setClickable(false);
				}
				
			}
		});
		
		
		btn_add_pic = (Button) findViewById(R.id.btn_add_pic);
		btn_add_pic.setOnClickListener(this);		
		et_username = (EditText) findViewById(R.id.et_username);
		et_disasename = (EditText) findViewById(R.id.et_disasename);
		et_disease_des = (EditText) findViewById(R.id.et_disease_des);
		TextView tv_upcase_des = (TextView) findViewById(R.id.tv_upcase_des);
		tv_upcase_des.setText(getStringBuilder("上传病例：（影像资料、检查报告、门诊病历、住院病历、出院小结等病史资料）", "上传病例："));
		
		
		RelativeLayout	rl_expert = (RelativeLayout) findViewById(R.id.rl_expert);
		if (parm_order_isteam) {
			rl_expert.setVisibility(View.GONE);
		}else {
			rl_expert.setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.tv_expert_name)).setText(parm_doctor_name);
		}
		
		((TextView) findViewById(R.id.tv_faculty_name))
				.setText(parm_doctor_dept);
		((TextView) findViewById(R.id.tv_hospital_name))
				.setText(parm_doctor_hp);

		noScrollgridview = (NoScrollGridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));

		adapter = new GridAdapter(this);
		noScrollgridview.setAdapter(adapter);

		noScrollgridview
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (arg2 == dataChoosed.size()) {

							// IntentHelper.getInstance(activity).gotoActivity(ImageGridActivity.class,
							// null, 1011);
							Intent intent = new Intent(activity,
									ImageGridActivity.class);
							startActivityForResult(intent, 1011);
							// intent.putExtra("isDymic", true);
							// startActivity(intent);
						} else {
							Intent intent = new Intent(activity,
									PhotoActivity.class);
							intent.putExtra("ID", arg2);
							startActivityForResult(intent, 1012);
						}
					}
				});
	}

	@SuppressWarnings("unchecked")
	private void doNet() {

		LoadingDialog.getInstance(activity).show();
		String userName = ((EditText) findViewById(R.id.et_username)).getText()
				.toString();
		String disaseName = ((EditText) findViewById(R.id.et_disasename))
				.getText().toString();
		
		EditText et_dsc =  ((EditText) findViewById(R.id.et_disease_des));
		String disaseDes = et_dsc.getText().toString();
		
		
		String account = CommonUtils.getMobile(activity);
		String token = CommonUtils.getToken(activity);
		Map map = new HashMap<String, Object>();
		map.put("username", account);
		map.put("token", token);
		map.put("mobile", account);
		
		map.put("contact_name", userName);
		
		if (parm_order_isteam) {
			map.put("hp_dept_id", parm_doctor_id);
		} else {
			map.put("doctor_id", parm_doctor_id);
		}

		map.put("disease_name", disaseName);
		map.put("disease_detail", disaseDes);
		if(is_commonweal){
			map.put("is_commonweal", "1");
		}else{
			map.put("is_commonweal", "0");
		}
		map.put("key", "booking");
		
//		getHttpResult(CommonUtils.getBookingUrl(activity), Constants.HTTP_INDEX.First, new TypeToken<QjResult<OrderResutEntity>>() {});
//		
//		
		postHttpResult(CommonUtils.getBookingUrl(activity), map, Constants.HTTP_INDEX.First, new TypeToken<QjResult<OrderResutEntity>>() {});
//		
//		QJNetUICallback callback = new QJNetUICallback<QjResult<OrderResutEntity>>(getApplicationContext(),CreateOrderActivity.class.getSimpleName()) {
//			@Override
//			public void onSuccess(final QjResult<OrderResutEntity> result) {
//				if (result != null) {
//					
//				}
//			}
//			public void onCompleted(Exception e, QjResult<OrderResutEntity> result) {
//				super.onCompleted(e, result);
//				LoadingDialog.getInstance(activity).dismiss();
//			}
//		};
//		String path = DataHandler.postDataObject(CommonUtils.getBookingUrl(activity),map, new TypeToken<QjResult<OrderResutEntity>>() {}, callback);
		
	}
	
	
	@Override
	public void onSuccess(QjResult result, String flg) {
		super.onSuccess(result, flg);
		ToastUtil.showToast(activity, "预约单提交成功！",Toast.LENGTH_SHORT);

		OrderResutEntity entity = (OrderResutEntity) result.getResults();
//				uploadFile(entity.getBooking_id(),entity.getActionUrl());//**************************
		if(entity != null){
			bookingId=entity.getBooking_id();
			String refNo = entity.getRefNo();
			payUrl = CommonUtils.getPayUrl(activity, refNo);
			if (dataChoosed != null && dataChoosed.size() > 0) {
				upQiniu();
			} else {
				gotoResultView();
			}
		}
		
	}
	
	@Override
	public void onCompleted(Exception e, String flg) {
		super.onCompleted(e, flg);
		LoadingDialog.getInstance(activity).dismiss();
	}
	
	

	@Override
	public void initHeaderView() {
		setTopViewBg(R.color.actionbar_bg_color);
		setTitleViewValue(R.string.person_order, 0, R.color.white);
		initBackView(R.drawable.left_back_white_icon, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
				dlg.setOk( "确定" );
				dlg.showAlertDialog(
						"你确定要放弃编辑吗？",
						new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								finish();
							}
						});
			}
		});
	}

	private void gotoResultView() {
		Intent intent = new Intent(activity,PayViewActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(Constants.PARM_ACTION_URL, payUrl);
		bundle.putString(Constants.PARM_PAGE_TITLE, "支付");
		intent.putExtras(bundle);
		startActivityForResult(intent, 1);
	}

	public void onDataCommit(View view) {
		if (!checkContent()) {
			return;
		}

		if (dataChoosed != null && dataChoosed.size() > 0) {
			AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
			dlg.setOk( "提交" );
			dlg.showAlertDialog(
					"您已经选中了" + dataChoosed.size() + "张影像资料,确认提交！",
					new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							doNet();
						}
					});
		} else {
			AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
			dlg.setOk( "提交" );
			dlg.setContent2(true, "（可以在预约单详情界面添加）" );
			dlg.showAlertDialog(
					"您尚未上传影像资料,确认提交？",
					new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							doNet();
						}
					});
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode==1) {
			IntentHelper.getInstance(activity).gotoActivity(OrderListActivity.class);
			finish();
		}else {
			dataChoosed = BimpTempHelper.getInstance().getImageItemsChoosend();
			// if(dataChoosed != null && dataChoosed.size() > 0){
			noScrollgridview.setAdapter(adapter);
			// }
		}
		
		
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case SUCCESS:
				progressDialog.dismiss();
				Toast.makeText(activity, "上传成功！", 2000).show();
				gotoResultView();
				break;

			case FAIL:
				progressDialog.dismiss();
				Toast.makeText(activity, "上传失败！", 2000).show();
				break;

			default:
				break;
			}
		}
	};

	
	
	
   private void upQiniu() {
	   progressDialog.show();
		final List<File> files = new ArrayList<File>();
		for (int i = 0; i < dataChoosed.size(); i++) {
			files.add(new File(dataChoosed.get(i).imagePath));
			//Toast.makeText(activity, "files大小"+files.get(i).length()/1024, Toast.LENGTH_LONG).show();
		}
		
		UploadUtils uploadUtils =new UploadUtils( bookingId);
		
		uploadUtils.uploadFiles(activity, null, files, new OnLoadListener() {
			
			@Override
			public void onLoadSuccess(String remoteDomain ,String key, String str, int index) {
				//Toast.makeText(activity, index+" onLoadSuccess "+str + index, Toast.LENGTH_LONG).show();
				doTestNet(remoteDomain ,files.get(index), index  ,key);
				
			}
			
			@Override
			public void onLoadSuccess(String remoteDomain ,String key, String str) {
//				Toast.makeText(activity, "onLoadSuccess /n"+str, Toast.LENGTH_LONG).show();
//				doTestNet( remoteDomain,  files.get(0));
				LoadingDialog.getInstance(activity).dismiss();
			}
			
			@Override
			public void onLoadFail() {
				progressDialog.dismiss();
				LoadingDialog.getInstance(activity).dismiss();
				Toast.makeText(activity, "上传失败！", Toast.LENGTH_LONG).show();
				
			}
		});
		
	}
	
  //上传七牛成功数据保存至自己服务器
  	@SuppressWarnings("unchecked")
  	private void doTestNet(String remoteDomain ,File file ,final int index, String key) {

  		Map map = new HashMap<String, Object>();
  		
  		map.put("appFile[token]", CommonUtils.getToken(activity));
  		map.put("appFile[username]", CommonUtils.getMobile(activity));
  		
  		map.put("appFile[size]", file.length()/1024+"");
  		if (file.getName().endsWith(".png")) {
  			map.put("appFile[type]", "png");
  		}else {
  			map.put("appFile[type]", "jpg");
  		}
  		
  		map.put("appFile[remoteDomain]", remoteDomain);
  		map.put("appFile[remoteKey]", key);
  		
  		map.put("appFile[bookingId]", bookingId);
  		
  		
  		
  		QJNetUICallback2 callback = new QJNetUICallback2<QjResult<HashMap<String, Object>>>(activity) {
			@Override
			public void onSuccess(QjResult<HashMap<String, Object>> result) {
				if (result != null) {
						if (index+1 ==dataChoosed.size()) {
							//ToastUtil.showToast(activity, "提交自己服务器成功！",Toast.LENGTH_LONG);
							mHandler.sendEmptyMessage(SUCCESS);
					} 
					}else {
						mHandler.sendEmptyMessage(FAIL);
				}
			}

			public void onError(Exception e, QjResult<HashMap<String, Object>> result) {
				super.onError(e, result);
				  ToastUtil.showToast(activity, "提交自己服务器失败！",Toast.LENGTH_LONG);
				mHandler.sendEmptyMessage(FAIL);
			}

			public void onCompleted(Exception e, QjResult<HashMap<String, Object>> result) {
				super.onCompleted(e, result);
			}
		};
		NetOld.with(activity).fetch( SystemConfig.SAVE_APP_FILE ,map, new TypeToken<QjResult<HashMap<String, Object>>>() {}, callback);
  		
  		
  		
//  		String url = NetHelper.getPostEncryptUrl(UploadUtils.saveappfile);
//  		map.put("sign", NetHelper.getPostSignParam(url));
//  		Net.with(activity).fetch(url, map,
//  				new TypeToken<QjResult<HashMap<String, Object>>>() {
//  				}, new QJNetUICallback<QjResult<HashMap<String, Object>>>(activity) {
//  					@Override
//  					public void onSuccess(QjResult<HashMap<String, Object>> result) {
//  						if (result != null) {
//  							if (index+1 ==dataChoosed.size()) {
//  								//ToastUtil.showToast(activity, "提交自己服务器成功！",Toast.LENGTH_LONG);
//	  							mHandler.sendEmptyMessage(SUCCESS);
//							} 
//  						}else {
//  							mHandler.sendEmptyMessage(FAIL);
//						}
//  						
//  					}
//  					
//  					@Override
//  					public void onError(Exception e,
//  							QjResult<HashMap<String, Object>> result) {
//  						super.onError(e, result);
//  						  ToastUtil.showToast(activity, "提交自己服务器失败！",Toast.LENGTH_LONG);
//  						mHandler.sendEmptyMessage(FAIL);
//  					}
//
//  					@Override
//  					public void onCompleted(Exception e,
//  							QjResult<HashMap<String, Object>> result) {
//  						super.onCompleted(e, result);
//  						
//  					}
//  				});

  	}
	

	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			if (dataChoosed.size() == Constants.PHOTO_MAX_SIZE) {
				return Constants.PHOTO_MAX_SIZE;
			}
			return (dataChoosed.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.myablum_item, parent,
						false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.blum_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (position == dataChoosed.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == Constants.PHOTO_MAX_SIZE|| !isAdd) {
					holder.image.setVisibility(View.GONE);
					convertView.setVisibility(View.GONE);
				}

			} else {
				cache.displayBmp(holder.image,
						dataChoosed.get(position).imagePath, handler);
			}
			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		BimpTempHelper.getInstance().clearData();
		super.onDestroy();
	}



	private boolean checkContent() {
		boolean flag = true;

		userName = et_username.getText().toString();
		disaseName = et_disasename.getText().toString();
		disaseDes = et_disease_des.getText().toString();

		if (TextUtils.isEmpty(userName)) {
			et_username.requestFocus();
			Toast.makeText(activity, "请填写患者名字！", 0).show();
			flag = false;
			return flag;
		}
		
		if (userName.length()>10) {
			et_username.requestFocus();
			Toast.makeText(activity, "患者姓名不超过10个字！", 0).show();
			flag = false;
			return flag;
		}
		
		if (TextUtils.isEmpty(disaseName)) {
			et_disasename.requestFocus();
			Toast.makeText(activity, "请填写疾病名称！", 0).show();
			flag = false;
			return flag;
		}
		if (TextUtils.isEmpty(disaseDes)) {
			et_disease_des.requestFocus();
			Toast.makeText(activity, "请填写疾病描述！", 0).show();
			flag = false;
			return flag;
		}
		
		if(disaseDes.length()<10){
			et_disease_des.requestFocus();
			ToastUtil.showToast(this, "病情描述至少10字！");
			flag = false;
			return flag;
		}

		return flag;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_add_pic:
//			isAdd = true;
//			btn_add_pic.setVisibility(View.GONE);
//			Intent intent = new Intent(activity,ImageGridActivity.class);
//			startActivityForResult(intent, 1011);
			break;
			
			
		case R.id.tv_agreement:
			Bundle bundle = new Bundle();
			bundle.putString(Constants.PARM_ACTION_URL, "http://m.mingyizhudao.com/mobile/user/index/page/aboutAgreement/header/0");
			bundle.putString(Constants.PARM_PAGE_TITLE, "名医主刀服务协议");
			
			IntentHelper.getInstance(activity).gotoActivity(WebViewActivity.class, bundle);
			break;
		default:
			break;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			AlertDialogs.getAlertDialog(activity).showAlertDialog("你确定要放弃编辑吗？", new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					finish();
				}
			});
		}
		return super.onKeyDown(keyCode, event);
	}

	
	private SpannableStringBuilder getStringBuilder(String text,String flg) {
	   	 if (text==null) {
	   		 text="";
			}
	        SpannableStringBuilder builder = new SpannableStringBuilder(text);
	       // ForegroundColorSpan yellowSpan = new ForegroundColorSpan(activity.getResources().getColor(R.color.lab_default_color));
	        if (flg!=null&&flg.length()>0&&text.contains(flg)) {
	       	 builder.setSpan(new TextAppearanceSpan(this, R.style.order_textview), text.indexOf(flg), text.indexOf(flg)+flg.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
	        
			return builder;
		}
}
